package tezhongbing;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceTest {
	public final static AtomicReference<String> ATOMIC_REFERENCE = new AtomicReference<String>("abc");
	private final static Random RANDOM_OBJECT = new Random();
	
	public static void main(String[] args) throws InterruptedException {
		final CountDownLatch startCountDown = new CountDownLatch(1);
		Thread[] threads = new Thread[20];
		for (int i = 0; i < threads.length; i++) {
			final int num = i;
			threads[i] = new Thread(){
				public void run() {
					String oldValue = ATOMIC_REFERENCE.get();
					try {
						startCountDown.await();
						Thread.sleep(RANDOM_OBJECT.nextInt() & 1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					if(ATOMIC_REFERENCE.compareAndSet(oldValue, oldValue+num)){//不能防止ABA的问题发生
						System.out.println("线程："+num+"，进行了对象修改！");
					}
				}
			};
			threads[i].start();
		}
		Thread.sleep(200);
		startCountDown.countDown();
		for(Thread thread : threads){
			thread.join();
		}
		System.out.println("最终结果为："+ATOMIC_REFERENCE.get());
	}
}
